package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constans.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.mapper.OrderInfoMapper;
import com.atguigu.gmall.payment.mapper.PaymentInfoMapper;
import com.atguigu.gmall.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * @author 李旭
 * @date 2022/1/23 10:26
 * @Description:
 */
@Service
public class PaymentServiceImpl implements PaymentInfoService {

    @Autowired
    private PaymentInfoMapper paymentInfoMapper;
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    //创建支付信息表
    @Override
    public PaymentInfo savePaymentInfo(Long orderId, PaymentType paymentType) {
        //1:幂等性问题
        //1:先查询是否已经创建了支付信息表
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderId, orderId));
        if(null != paymentInfo){
            //2:创建了  直接返回
            //更新支付类型 （微信 还是支付宝）
            paymentInfo.setPaymentType(paymentType.name());
            //创建时间
            paymentInfo.setCreateTime(new Date());
            paymentInfoMapper.updateById(paymentInfo);

        }else{
            //3:未创建  创建支付信息表
            paymentInfo = new PaymentInfo();
            //
            OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
            paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
            paymentInfo.setOrderId(orderInfo.getId());
            paymentInfo.setPaymentType(paymentType.name());
            paymentInfo.setTotalAmount(orderInfo.getTotalAmount());
            paymentInfo.setSubject(orderInfo.getTradeBody());
            paymentInfo.setPaymentStatus(PaymentStatus.UNPAID.name());
            //创建时间
            paymentInfo.setCreateTime(new Date());
            paymentInfoMapper.insert(paymentInfo);
        }
        //返回
        return paymentInfo;
    }


    //更新支付表的信息
    @Override
    public void updatePaymentInfo(Map<String, String> paramsMap) {
        //存在 幂等性问题  重复更新支付表的信息
        //1:查询  判断是否是支付中  改成已支付
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOutTradeNo, paramsMap.get("out_trade_no")));
        if(null != paymentInfo && PaymentStatus.UNPAID.name().equals(paymentInfo.getPaymentStatus())){
            //支付中
            paymentInfo.setPaymentStatus(PaymentStatus.PAID.name());
            //银行流水号
            paymentInfo.setTradeNo(paramsMap.get("trade_no"));
            //回调时间
            paymentInfo.setCallbackTime(new Date());
            //回调内容
            paymentInfo.setCallbackContent(JSONObject.toJSONString(paramsMap));

            paymentInfoMapper.updateById(paymentInfo);

            //发消息  更新订单相关信息
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_PAYMENT_PAY,
                    MqConst.ROUTING_PAYMENT_PAY,paymentInfo.getOrderId());

        }

        //{
        // gmt_create=2022-02-08 11:19:20,
        // charset=utf-8,
        // gmt_payment=2022-02-08 11:19:30,
        // notify_time=2022-02-08 11:19:32,
        // subject=Apple iPhone 11 (A2223) 128GB 黑色 移动联通电信4G手机 双卡双待 Apple iPhone 11 (A2223) 128GB 红色 移动联通电信4G手机 双卡双待 Ap,
        // sign=qf6ChnKsT3nRfAzU8oxL9WunjTt7TFW/i8dm+Ml+Cc+w4y56JUV8kWoKrKnsxxWQCs0cjxyRv9v7VbolDCxSBQJRYNajl2nLeFCWATba2F+QmvIuV6vbnHemCOXP/Nm5h0o8YOT3fTT/ylrEpxVjS7zGtchOmjZGp3vw5jRjkrf6gDneSYvf+eu9q03e2shM7ZPyOWEwEFgXXA8zqLyc1OEAjoGU7HFyqT+EQVZoj7ZJZBbkcqk1isf3XgdSLrZQSWcuoNFPV1wGWZ90VZgDo7prUmabSSJpcvsN2OiKvvqmS4VuId+DTspc5HdGs5YnwElgj7whS3Bt+mO69yvyEA==,
        // buyer_id=2088102181130586,
        // invoice_amount=76822.00,
        // version=1.0,
        // notify_id=2022020800222111931030580521515831,
        // fund_bill_list=[{
        // amount":"76822.00",
        // "fundChannel":"ALIPAYACCOUNT"}], notify_type=trade_status_sync,
        // out_trade_no=ATGUIGU1644290338499457,
        // total_amount=76822.00,
        // trade_status=TRADE_SUCCESS,
        // trade_no=2022020822001430580501993290,
        // auth_app_id=2016102100732915,
        // receipt_amount=76822.00, point_amount=0.00,
        // app_id=2016102100732915,
        // buyer_pay_amount=76822.00,
        // sign_type=RSA2,
        // seller_id=2088102180533564}





    }
    @Autowired
    private RabbitService rabbitService;
}
